package com.wfg.nettydemo.io.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author wufagang
 * @description 启动之后使用telnet ip 端口 进行测试
 * ps： telnet 127.0.0.1 9999
 * @date 2022年05月28日 09:56
 */
public class BIOServer {


    public static void main(String[] args) throws IOException {
        //线程池机制
        //思路
        //1. 创建一个线程池
        //2. 如果有客户端连接，就创建一个线程，与之通讯(单独写一个方法)
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务启动");
        while (true){
            System.out.println("thread id = " + Thread.currentThread().getId()+ "等待链接");
            //获取不到链接会阻塞 等待
            Socket accept = serverSocket.accept();
            System.out.println("thread id = " + Thread.currentThread().getId()+ "获得一个客户端");
            newCachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    hander(accept);
                }
            });
        }
    }

    private static void hander(Socket socket) {

        try {
            System.out.println("thread id = " + Thread.currentThread().getId()+ "处理消息");
            byte[] bytes = new byte[1024];
            InputStream inputStream = socket.getInputStream();
            while (true){
                int read = inputStream.read(bytes);
                if(read == -1) break;
                System.out.println("thread id = " + Thread.currentThread().getId()+ "读到消息："+new String(bytes,0, read));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
